package com.deke.security.utils;

import com.deke.entity.AclUser;
import com.deke.utils.JwtTool;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2022/12/2 17:59
 * @description：获取web对象的工具类
 * @modified By：
 * @version:
 **/
public class WebUtils {
    
    /**
     * @create by: Username 刘亦辰 
     * @description: 随时随地获取request的工具 
     * @create time: 2022/12/2 18:47
     * @param null
     * @return :  
     **/
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            return null;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        return  request;
    }

    /**
     * @create by: Username 刘亦辰 
     * @description:  随时随地获取response的工具 
     * @create time: 2022/12/2 18:53
     * @param null
     * @return :  
     **/
    public static HttpServletResponse getResponse(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            return null;
        }
        HttpServletResponse response = requestAttributes.getResponse();
        return  response;
    }

    /**
     * @create by: Username 刘亦辰 
     * @description: 获取登录后的用户信息 
     * @create time: 2022/12/3 20:35
     * @param null
     * @return :  
     **/
    public static String getUsername(){
        HttpServletRequest request = getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenClaim = JwtTool.getTokenClaim(token);
        String username = tokenClaim.get("username").toString();
        return username;
    }
}